from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QLabel, 
                               QTimeEdit, QDoubleSpinBox, QPushButton)
from PyQt6.QtCore import QTimer, QTime, pyqtSignal
from PyQt6.QtGui import QFont
from styles import (AMOUNT_WIDGET_STYLE, TIME_WIDGET_STYLE,
                   START_BUTTON_STYLE, STOP_BUTTON_STYLE)
import json
import os

class SalaryTimer(QWidget):
    """工资计时器组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.start_time = QTime(9, 0)  # 默认上班时间 9:00
        self.end_time = QTime(17, 0)   # 默认下班时间 17:00
        self.break_start = QTime(12, 0) # 默认休息开始时间 12:00
        self.break_end = QTime(13, 0)   # 默认休息结束时间 13:00
        self.daily_salary = 0.0         # 日薪
        self.earned_amount = 0.0        # 已赚金额
        self.is_running = True          # 默认运行状态
        
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_timer)
        
        self.init_ui()
        self.load_settings()
        self.timer.start(1000)  # 启动时自动开始计时
        
    def init_ui(self):
        """初始化UI界面"""
        layout = QVBoxLayout()
        layout.setSpacing(20)
        layout.setContentsMargins(30, 30, 30, 30)
        
        # 标题
        title = QLabel("工作计时器")
        title.setFont(QFont("Microsoft YaHei", 18, QFont.Weight.Bold))
        title.setStyleSheet("color: #24292e; margin-bottom: 10px;")
        layout.addWidget(title)
        
        # 创建金额显示区域
        amount_widget = QWidget()
        amount_widget.setStyleSheet(AMOUNT_WIDGET_STYLE)
        amount_layout = QVBoxLayout(amount_widget)
        amount_layout.setSpacing(5)
        
        amount_title = QLabel("当前收入")
        amount_title.setFont(QFont("Microsoft YaHei", 13))
        amount_title.setStyleSheet("color: #57606a;")
        amount_layout.addWidget(amount_title)
        
        self.amount_label = QLabel("¥0.00")
        self.amount_label.setFont(QFont("Microsoft YaHei", 28, QFont.Weight.Bold))
        self.amount_label.setStyleSheet("color: #238636;")
        amount_layout.addWidget(self.amount_label)
        
        layout.addWidget(amount_widget)
        
        # 创建时间信息区域
        time_widget = QWidget()
        time_widget.setStyleSheet(TIME_WIDGET_STYLE)
        time_layout = QVBoxLayout(time_widget)
        time_layout.setSpacing(15)
        
        # 已工作时长
        worked_container = QWidget()
        worked_layout = QVBoxLayout(worked_container)
        worked_layout.setSpacing(5)
        worked_layout.setContentsMargins(0, 0, 0, 0)
        
        worked_title = QLabel("已工作时长")
        worked_title.setProperty("type", "title")
        worked_layout.addWidget(worked_title)
        
        self.worked_time_label = QLabel("0:00:00")
        self.worked_time_label.setProperty("type", "value")
        self.worked_time_label.setStyleSheet("color: #0969da;")
        worked_layout.addWidget(self.worked_time_label)
        
        time_layout.addWidget(worked_container)
        
        # 剩余时长
        remaining_container = QWidget()
        remaining_layout = QVBoxLayout(remaining_container)
        remaining_layout.setSpacing(5)
        remaining_layout.setContentsMargins(0, 0, 0, 0)
        
        remaining_title = QLabel("剩余工作时长")
        remaining_title.setProperty("type", "title")
        remaining_layout.addWidget(remaining_title)
        
        self.remaining_time_label = QLabel("8:00:00")
        self.remaining_time_label.setProperty("type", "value")
        self.remaining_time_label.setStyleSheet("color: #cf222e;")
        remaining_layout.addWidget(self.remaining_time_label)
        
        time_layout.addWidget(remaining_container)
        
        layout.addWidget(time_widget)
        layout.addSpacing(10)
        
        layout.addStretch()
        self.setLayout(layout)
    
    def load_settings(self):
        """从配置文件加载设置"""
        if os.path.exists('settings.json'):
            try:
                with open('settings.json', 'r') as f:
                    settings = json.load(f)
                    self.daily_salary = float(settings.get('daily_salary', 0.0))
                    self.start_time = QTime.fromString(settings.get('start_time', '09:00'), 'HH:mm')
                    self.end_time = QTime.fromString(settings.get('end_time', '17:00'), 'HH:mm')
                    self.break_start = QTime.fromString(settings.get('break_start', '12:00'), 'HH:mm')
                    self.break_end = QTime.fromString(settings.get('break_end', '13:00'), 'HH:mm')
            except:
                pass
    
    def save_settings(self):
        """保存设置到配置文件"""
        settings = {
            'daily_salary': self.daily_salary,
            'start_time': self.start_time.toString('HH:mm'),
            'end_time': self.end_time.toString('HH:mm'),
            'break_start': self.break_start.toString('HH:mm'),
            'break_end': self.break_end.toString('HH:mm')
        }
        with open('settings.json', 'w') as f:
            json.dump(settings, f)
    
    def is_break_time(self):
        """判断当前是否是休息时间"""
        current_time = QTime.currentTime()
        return (current_time >= self.break_start and 
                current_time < self.break_end)
    
    def calculate_per_second_salary(self):
        """计算每秒收入"""
        total_seconds = self.start_time.secsTo(self.end_time)
        break_seconds = self.break_start.secsTo(self.break_end)
        working_seconds = total_seconds - break_seconds
        return self.daily_salary / working_seconds if working_seconds > 0 else 0
    
    def update_timer(self):
        """更新计时器显示"""
        current_time = QTime.currentTime()
        worked_seconds = self.start_time.secsTo(current_time)
        remaining_seconds = current_time.secsTo(self.end_time)
        
        # 更新已工作时长
        hours = worked_seconds // 3600
        minutes = (worked_seconds % 3600) // 60
        seconds = worked_seconds % 60
        self.worked_time_label.setText(f"{hours}:{minutes:02d}:{seconds:02d}")
        
        # 更新剩余工作时长
        hours = remaining_seconds // 3600
        minutes = (remaining_seconds % 3600) // 60
        seconds = remaining_seconds % 60
        self.remaining_time_label.setText(f"{hours}:{minutes:02d}:{seconds:02d}")
        
        # 计算当前收入
        if not self.is_break_time():
            total_seconds = self.start_time.secsTo(self.end_time)
            break_seconds = self.break_start.secsTo(self.break_end)
            working_seconds = total_seconds - break_seconds
            
            # 计算当前时间点应得的收入比例
            current_ratio = worked_seconds / working_seconds
            self.earned_amount = self.daily_salary * current_ratio
            self.amount_label.setText(f"¥{self.earned_amount:.2f}")
        
        # 检查是否到达下班时间
        if current_time >= self.end_time:
            self.stop_timer()
    
    def toggle_timer(self):
        """切换计时器状态"""
        if self.is_running:
            self.stop_timer()
        else:
            self.start_timer()
    
    def start_timer(self):
        """开始计时"""
        self.is_running = True
        self.timer.start(1000)  # 每秒更新一次
    
    def stop_timer(self):
        """停止计时"""
        self.is_running = False
        self.timer.stop() 